package com.young.netty.server;

import com.young.netty.ServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Singleton;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;

@Slf4j
@Singleton
@Component
public class NettyServer {

    private NioEventLoopGroup   bossEventLoopGroup;
    private NioEventLoopGroup workerEventLoopGroup;

    private           Channel              channel;

    @Async
    @PostConstruct
    public void init() throws Exception {
        bossEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        workerEventLoopGroup = new NioEventLoopGroup(4);
        log.info("==================== init netty server start ====================");
        start(new InetSocketAddress(3000));
        log.info("==================== init netty server end   ====================");
    }

    @PreDestroy
    private void destroy() {
        if (null != channel) {
            channel.close();
        }
        bossEventLoopGroup.shutdownGracefully();
        workerEventLoopGroup.shutdownGracefully();
    }

    public void start(InetSocketAddress address) {
        ServerBootstrap bootstrap =
            new ServerBootstrap()
                .group(bossEventLoopGroup, workerEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 2048)
                .childHandler(new ServerChannelInitializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        try {
            ChannelFuture cf = bootstrap.bind(address).sync();
            channel = cf.channel();
            log.info("Netty server success start at port [{}]", address.getPort());
        } catch (Exception e) {
            log.error("Netty server fail start at port [{}]", address.getPort(), e);
        }
    }

}
